package com.urea.web.controller.common;

import cn.hutool.core.io.FileUtil;
import com.urea.common.core.domain.AjaxResult;
import com.urea.common.utils.file.FileUtils;
import com.urea.framework.config.MinIOConfiguration;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.bean.WxAccessToken;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Api(tags = "文件相关")
public class FileController {

    @Resource
    private MinioClient minioClient;
    @Resource
    private MinIOConfiguration minIOConfiguration;
    @Value("${ruoyi.profile}")
    private String basePath;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        // 上传
        String path = UUID.randomUUID().toString(); // 文件名，使用 UUID 随机
         minioClient.putObject(PutObjectArgs.builder()
                .bucket(minIOConfiguration.getBucket()) // 存储桶
                .object(path) // 文件名
                .stream(file.getInputStream(), file.getSize(), -1) // 文件内容
                .contentType(file.getContentType()) // 文件类型
                .build());

        // 拼接路径
        return String.format("%s/%s/%s", minIOConfiguration.getEndpoint(), minIOConfiguration.getBucket(), path);
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/delete")
    public String delete(@RequestParam("path") String path) throws Exception {
        minioClient.removeObject(RemoveObjectArgs.builder()
                .bucket(minIOConfiguration.getBucket()) // 存储桶
                .object(path) // 文件名
                .build());
        return "success";
    }


    /**
     * 上传文件
     */
    @PostMapping("/baseUpload")
    @ApiOperation("文件上传")
    public AjaxResult uploadLocal(@RequestParam("file") MultipartFile file)  {
        // 获取文件目录
        String s = basePath + "/" + file.getOriginalFilename();
        File file1 = new File(s);
        try {
            FileUtil.writeFromStream(file.getInputStream(),file1);
        } catch (IOException e) {
            e.printStackTrace();
        }
       return AjaxResult.success();
    }
}